package com.yz.platform.modules.api.service.impl;

import com.google.common.collect.Maps;
import com.google.gson.Gson;

import com.yz.platform.common.exception.CommonException;
import com.yz.platform.common.task.UpdateCodeStatusTask;
import com.yz.platform.common.utils.Constant;
import com.yz.platform.modules.api.entity.AuthEntity;
import com.yz.platform.modules.api.service.AuthService;
import com.yz.platform.modules.biz.entity.ActivationCodeEntity;
import com.yz.platform.modules.biz.entity.CodeLogEntity;
import com.yz.platform.modules.biz.entity.ScriptEntity;
import com.yz.platform.modules.biz.service.ActivationCodeService;
import com.yz.platform.modules.biz.service.CodeLogService;
import com.yz.platform.modules.biz.service.ScriptService;
import com.yz.platform.modules.sys.service.SysConfigService;

import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * author:lin Date : 2017/10/16 下午9:24
 */
@Transactional(readOnly = true)
@Service("authService")
public class AuthServiceImpl implements AuthService {


    private Logger log = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ScriptService scriptService;

    @Autowired
    private ActivationCodeService codeService;

    @Autowired
    private CodeLogService codeLogService;

    /**
     * 激活码验证
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public boolean checkAuth(AuthEntity authEntity) throws CommonException {

        boolean result = false;

        ScriptEntity script = scriptService.getByScriptNo(authEntity.getScriptNo());

        if (script == null) {
            throw new CommonException("脚本编号不正确");
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("scriptId", script.getScriptId());
        params.put("code", authEntity.getKey());

        log.debug("checkAuth >>> " + "scriptId :" + script.getScriptId() + ",code:" + authEntity.getKey());

        List<ActivationCodeEntity> codeList = codeService.queryList(params);

        if (codeList == null || codeList.isEmpty()) {
            throw new CommonException("无效激活码");
        }

        //一个脚本，一个激活码，唯一，直接去Get（0）
        ActivationCodeEntity code = codeList.get(0);

        if (code.getStatus() == 1 || code.getStatus() == -1){
            throw new CommonException("激活码已失效");
        }

        /**
         * 查询是否有激活码日志
         */
        CodeLogEntity codeLog = codeLogService.queryBycode(authEntity.getKey());

        if (codeLog == null) {
            //第一次，启动，记录日志
            CodeLogEntity firstLog = new CodeLogEntity();
            firstLog.setCode(authEntity.getKey());
            firstLog.setDevices(authEntity.getDeviceNo());
            firstLog.setExecTimes(1);
            firstLog.setStartupTime(new Date());
            firstLog.setStatus(0);
            codeLogService.save(firstLog);
        } else {

            //验证有效期,暂时写死，后面修改从配置表中读取
            String expires = code.getExpires();

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(codeLog.getStartupTime());

            //使用10分钟
            if ("1".equals(expires)) {

                calendar.add(Calendar.MINUTE, 10);

            } else if ("2".equals(expires)) {

                calendar.add(Calendar.MONTH, 6);

            } else if ("3".equals(expires)) {
                calendar.add(Calendar.MONTH, 12);
            }

            if (System.currentTimeMillis() > calendar.getTime().getTime()) {

                UpdateCodeStatusTask task = new UpdateCodeStatusTask(code);
                new Thread(task).start();

                throw new CommonException("激活码已过期失效");
            }

            //验证设备
            String historyDevce = codeLog.getDevices();
            int len = historyDevce.split(",").length;
            int deviceCount = sysConfigService.getValue(Constant.DICT_DEVICE_COUNT) == null ?
                    5 : Integer.parseInt(sysConfigService.getValue(Constant.DICT_DEVICE_COUNT));
            if (len > deviceCount) {
                throw new CommonException("激活码支持的设备数量超过系统设置");
            } else if (!historyDevce.contains(authEntity.getDeviceNo())) {
                historyDevce = historyDevce + "," + authEntity.getDeviceNo();
            }

            //更新日志
            codeLog.setExecTimes(codeLog.getExecTimes() + 1);
            codeLog.setDevices(historyDevce);
            codeLogService.update(codeLog);
        }

        code.setStatus(2);//更新成使用中状态
        codeService.update(code);

        result = true;

        return result;

    }


}
